﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using MetaSearch.searchbing;
using Microsoft.SharePoint;
using SPManagerLib;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Collections;
using System.Text;

/*
Developed By: Jyoti Seth
Developed On: 24th Nov 2010
Description: Code is written to integrate bing search functionality. 
             Saving the results to "Bookmarks" and "Save Query".
Modified On: 3rd Mar 2011
Description: Added code to integrate UKPMC Search also.
 */
namespace MetaSearch.Search_Literature
{
    public partial class Search_LiteratureUserControl : UserControl
    {
        private uint offset;
        private uint total;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    pnlQueryDesc.Visible = false;

                    // Create Bookmarks list
                    AddBookmarksList();

                    // Create Savedquery list
                    AddSavedQueryList();

                    ViewState["CurrentSearch"] = "bing";
                    lnkUKPMCSearch.Attributes.Add("style", "font-weight:normal;");
                    lnkBingSearch.Attributes.Add("style", "font-weight:bold;");


                    // If the page is opened with the url saved in saved query, it will check the values in the query strings
                    // And search accordingly where
                    // Key1 = Search Text, key2 = Which Search Source is currently active
                    // Key3 = Bing Search Check Box Value, key4 = UKPMC Search Check Box Value
                    if (Request.QueryString["key1"] != "" && Request.QueryString["key1"] != null)
                    {
                        txtSearch.Text = Request.QueryString["key1"].ToString();
                        lblResults.Text = String.Empty;
                        lblPageText.Text = String.Empty;
                        ViewState["offset"] = 0;
                        ViewState["total"] = 0;
                        offset = 0;
                        if (Request.QueryString["key2"] != "" && Request.QueryString["key2"] != null)
                        {
                            ViewState["CurrentSearch"] = Request.QueryString["key2"].ToString();
                        }
                        if (Request.QueryString["key3"] != "" && Request.QueryString["key3"] != null)
                        {
                            chkSearchSources.Items[0].Selected = Convert.ToBoolean(Request.QueryString["key3"].ToString());
                            if (chkSearchSources.Items[0].Selected)
                                lnkBingSearch.Visible = true;
                        }
                        if (Request.QueryString["key4"] != "" && Request.QueryString["key4"] != null)
                        {
                            chkSearchSources.Items[1].Selected = Convert.ToBoolean(Request.QueryString["key4"].ToString());
                            if (chkSearchSources.Items[1].Selected)
                                lnkUKPMCSearch.Visible = true;

                        }
                        if (ViewState["CurrentSearch"].ToString() == "bing")
                        {
                            ResetValues();
                            SearchAndBindBingText(offset);
                            grdBingSearch.Visible = true;
                            grdUKPMCSearch.Visible = false;
                            lnkUKPMCSearch.Attributes.Add("style", "font-weight:normal;");
                            lnkBingSearch.Attributes.Add("style", "font-weight:bold;");
                        }
                        else
                        {
                            ResetValues();
                            SearchAndBindUKPMCText(offset);
                            grdBingSearch.Visible = false;
                            grdUKPMCSearch.Visible = true;
                            lnkUKPMCSearch.Attributes.Add("style", "font-weight:bold;");
                            lnkBingSearch.Attributes.Add("style", "font-weight:normal;");
                        }

                    }
                    mvwStudyPlanning.ActiveViewIndex = 0;
                }
                catch (Exception ex)
                {
                    lblResults.Text = ex.Message;
                }
            }
           
        }

        // To display the message in the message box
        private void MessageBox(string msg)
        {
           Label lbl = new Label();
            lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";
            Page.Controls.Add(lbl);
        }

        //protected void LinkReviewLiteratureReviewLiterature_Click(object sender, EventArgs e)
        //{
        //    pnlReviewLiterature.Visible = true;
        //}

        /* Commented by Jyoti Seth on 3rd Mar 2011 as need to remove Bookmarks and Saved Queries link */

        //// Go to the Saved Query Page when user clicks on "Saved Query"
        //protected void LinkSavedQuery_Click(object sender, EventArgs e)
        //{
        //    PanelReviewLiteratureReviewLiterature.Visible = false;

        //    string urlWeb = SPContext.Current.Web.Url.ToString();
        //    string urlSavedQuery = urlWeb + "/Lists/Saved Queries/AllItems.aspx";
        //    Response.Redirect(urlSavedQuery);
        //}

        //// Go to the Saved Query Page when user clicks on "Bookmarks"
        //protected void LinkBookmarks_Click(object sender, EventArgs e)
        //{
        //    PanelReviewLiteratureReviewLiterature.Visible = false;

        //    string urlWeb = SPContext.Current.Web.Url.ToString();
        //    string urlBookmarks = urlWeb + "/Lists/Bookmarks/AllItems.aspx";
        //    Response.Redirect(urlBookmarks);
        //}   

        // It will show the results according to UKPMC search. 
        protected void lnkUKPMCSearch_Click(object sender, EventArgs e)
        {
            ResetValues();
            SearchAndBindUKPMCText(offset);
            grdBingSearch.Visible = false;
            grdUKPMCSearch.Visible = true;
            lnkUKPMCSearch.Attributes.Add("style", "font-weight:bold;");
            lnkBingSearch.Attributes.Add("style", "font-weight:normal;");
            ViewState["CurrentSearch"] = "UKPMC";

        }

        // It will show the results according to Bing Search
        protected void lnkBingSearch_Click(object sender, EventArgs e)
        {
            ResetValues();
            SearchAndBindBingText(offset);
            grdBingSearch.Visible = true;
            grdUKPMCSearch.Visible = false;
            lnkUKPMCSearch.Attributes.Add("style", "font-weight:normal;");
            lnkBingSearch.Attributes.Add("style", "font-weight:bold;");
            ViewState["CurrentSearch"] = "bing";
        }

        protected void btnSearch_Click(object sender, ImageClickEventArgs e)
        {
            ResetValues();
            // Search the text and show the results
            SearchAndBindText(offset);
        }


        // The following function will check whether the results to be fetched from Bing Search or UKPMC Search.
        // Call the appropriate search function and display the controls accordingly
        private void SearchAndBindText(uint searchOffset)
        {
            try
            {
                if (txtSearch.Text != String.Empty) // If there is any text available for search
                {
                    // If UKPMC Search Checkbox is checked and Bing Search Checkbox is not checked 
                    if (chkSearchSources.Items[1].Selected == true && chkSearchSources.Items[0].Selected == false)
                    {
                        SearchAndBindUKPMCText(searchOffset);

                        lnkUKPMCSearch.Visible = true;
                        lnkBingSearch.Visible = false;
                        grdUKPMCSearch.Visible = true;
                        grdBingSearch.Visible = false;
                        lnkUKPMCSearch.Text = "UKPMC Search ";
                        lnkBingSearch.Text = "";
                        lnkUKPMCSearch.Attributes.Add("style", "font-weight:bold;");
                        ViewState["CurrentSearch"] = "UKPMC";
                    }
                    // If Bing Search Check box checked and UKPMC checkbox not checked
                    else if (chkSearchSources.Items[0].Selected == true && chkSearchSources.Items[1].Selected == false)
                    {
                        SearchAndBindBingText(searchOffset);

                        lnkUKPMCSearch.Visible = false;
                        lnkBingSearch.Visible = true;
                        grdUKPMCSearch.Visible = false;
                        grdBingSearch.Visible = true;
                        lnkUKPMCSearch.Text = "";
                        lnkBingSearch.Text = "Bing Search";
                        lnkUKPMCSearch.Attributes.Add("style", "font-weight:bold;");
                        ViewState["CurrentSearch"] = "bing";
                    }
                    // If Both Bing Search and UKPMC Check box are checked. 
                    else if (chkSearchSources.Items[0].Selected == true && chkSearchSources.Items[1].Selected == true)
                    {
                        lnkUKPMCSearch.Visible = true;
                        lnkBingSearch.Visible = true;
                        lnkUKPMCSearch.Text = "UKPMC Search ";
                        lnkBingSearch.Text = "Bing Search";
                        if (ViewState["CurrentSearch"].ToString() == "bing") // If currect selected search is for Bing
                        {
                            SearchAndBindBingText(searchOffset);
                            grdBingSearch.Visible = true;
                            grdUKPMCSearch.Visible = false;
                            lnkUKPMCSearch.Attributes.Add("style", "font-weight:normal;");
                            lnkBingSearch.Attributes.Add("style", "font-weight:bold;");
                        }
                        else
                        {
                            SearchAndBindUKPMCText(searchOffset);
                            grdBingSearch.Visible = false;
                            grdUKPMCSearch.Visible = true;
                            lnkUKPMCSearch.Attributes.Add("style", "font-weight:bold;");
                            lnkBingSearch.Attributes.Add("style", "font-weight:normal;");
                        }
                    }
                    else
                    {
                        MessageBox("Please check at least one Information Source.");
                    }
                }
                else
                {
                    MessageBox("Please enter text for search.");
                }
            }
            catch
            {
            }

        }

        // Search the text with Bing search and bind the results to the grid.
        // Integrated the web service to fetch Bing Search Results
        private void SearchAndBindBingText(uint searchOffset)
        {
            try
            {
                ViewState["itemsperpage"] = 10;
                divmessage.InnerHtml = "";

                // Integrate Web Service
                BingService soapClient = new BingService();
                SearchRequest request = new SearchRequest();
                request.AppId = "FCA24862135E6747D1000C9EBEDCE2E640EDB5E3";
                request.Sources = new SourceType[] { SourceType.Web };
                request.Query = txtSearch.Text;

                // Web-specific request fields (optional)
                request.Web = new WebRequest();
                request.Web.Count = 10;
                request.Web.CountSpecified = true;
                request.Web.Offset = (uint)searchOffset;
                request.Web.OffsetSpecified = true;

                SearchResponse response = soapClient.Search(request);

                DataTable dtSearchResult = new DataTable();
                dtSearchResult.Columns.Add("Title", typeof(string));
                dtSearchResult.Columns.Add("Description", typeof(string));
                dtSearchResult.Columns.Add("Url", typeof(string));
                dtSearchResult.Columns.Add("DateTime", typeof(string));

                // Fetch the search results from web service and copy it to datatable
                if (response.Web != null && response.Web.Total > 0)
                {
                    foreach (WebResult res in response.Web.Results)
                    {
                        DataRow drow = dtSearchResult.NewRow();
                        drow["Title"] = res.Title;
                        drow["Description"] = res.Description;
                        drow["Url"] = res.Url;
                        drow["DateTime"] = res.DateTime.ToString();
                        dtSearchResult.Rows.Add(drow);
                    }
                    DataSet dsSearch = new DataSet();
                    dsSearch.Tables.Add(dtSearchResult);

                    // Hide or display Previous and Next Buttons according to search results
                    btnPrev.Visible = dtSearchResult.Rows.Count > 0 ? true : false;
                    btnNext.Visible = dtSearchResult.Rows.Count > 0 ? true : false;

                    // Hide or display No of Pages and Save Bookmarks link according to search results
                    lblPageText.Visible = dtSearchResult.Rows.Count > 0 ? true : false;
                    lnkSaveBookmarks.Visible = dtSearchResult.Rows.Count > 0 ? true : false;

                    grdBingSearch.DataSource = dsSearch;

                    lnkBingSearch.Visible = true;

                    lnkUKPMCSearch.Text = "UKPMC Search ";
                    lnkBingSearch.Text = "Bing Search";

                    grdBingSearch.Visible = true;
                    lnkBingSearch.Attributes.Add("style", "font-weight:bold;");

                    // Bind the search results to the grid
                    grdBingSearch.DataBind();

                }

                total = response.Web.Total;
                ViewState["total"] = total;

                if (total > 0) // If search results are found 
                {
                    if ((offset + Convert.ToUInt32(ViewState["itemsperpage"])) < total)
                        lblPageText.Text = (offset + 1).ToString() + "-" + (offset + Convert.ToUInt32(ViewState["itemsperpage"])).ToString() + " of " + total.ToString();
                    else
                        lblPageText.Text = (offset + 1).ToString() + "-" + total.ToString() + " of " + total.ToString();
                    EnableDisableButtons(searchOffset, total);
                    btnSaveQuery.ImageUrl = "~/_layouts/SearchLiterature/Save-Query.png";
                    btnSaveQuery.Enabled = true;
                }
                else
                {
                    lblResults.Text = "We didn't find any results for " + txtSearch.Text;
                    lblPageText.Text = string.Empty;
                    btnNext.Enabled = false;
                    btnPrev.Enabled = false;
                    grdBingSearch.DataSource = null;
                    grdBingSearch.DataBind();
                }

            }

            catch
            {
            }

        }

        // Search the text with UKPMC search with RSS Feed URL and bind the results to the grid.
        private void SearchAndBindUKPMCText(uint searchOffset)
        {
            try
            {
                // Fetch the UKPMC search results from the UKPMC RSS Feed URL
                XDocument rssFeed = XDocument.Load("http://ukpmc.ac.uk/search/?page=" + ViewState["ukpmcpage"].ToString() + "&query=" + txtSearch.Text + "&opensearch=1&mode=rss");
                XNamespace opensearchSpace = rssFeed.Root.GetNamespaceOfPrefix("opensearch");
                XNamespace defaultSpace = rssFeed.Root.GetDefaultNamespace();

                uint totalResults = 0; // = rssFeed.Element(opensearchSpace + "totalResults").Value.ToString();

                // Find the total records and the no. of items displayed on page
                var results = (from item in rssFeed.Descendants("channel")
                               select new Feeds
                               {
                                   totalrecords = Convert.ToUInt32(item.Element(opensearchSpace + "totalResults").Value),
                                   itemsperpage = Convert.ToUInt32(item.Element(opensearchSpace + "itemsPerPage").Value)
                               });


                List<Feeds> resultsList = new List<Feeds>();
                resultsList = results.ToList();
                foreach (var listitem in resultsList)
                {
                    totalResults = listitem.totalrecords;
                    ViewState["itemsperpage"] = listitem.itemsperpage;
                }

                // Fetch the results from the RSS Feed URL
                var posts = (from item in rssFeed.Descendants("item")
                             select new Feeds
                             {
                                 title = item.Element("title").Value,
                                 link = item.Element("link").Value,
                                 description = item.Element("description").Value,
                                 author = item.Element("author") != null ? item.Element("author").Value : String.Empty
                             });

                //list feed data read
                List<Feeds> newsList = new List<Feeds>();
                newsList = posts.ToList();

                DataTable dtSearchResult = new DataTable();
                dtSearchResult.Columns.Add("Title", typeof(string));
                dtSearchResult.Columns.Add("Description", typeof(string));
                dtSearchResult.Columns.Add("Link", typeof(string));
                dtSearchResult.Columns.Add("Author", typeof(string));

                // Store the search results in Data Table
                foreach (var listitem in newsList)
                {
                    DataRow drow = dtSearchResult.NewRow();
                    drow["Title"] = listitem.title.ToString();
                    drow["Description"] = listitem.description.ToString().Trim();
                    drow["Link"] = listitem.link.ToString();
                    drow["Author"] = listitem.author.ToString();
                    dtSearchResult.Rows.Add(drow);
                }

                DataSet dsSearch = new DataSet();
                dsSearch.Tables.Add(dtSearchResult);


                //Bind the search results to the UKPMC grid and display and hide controls accordingly
                grdUKPMCSearch.DataSource = dsSearch;
                grdUKPMCSearch.DataBind();

                btnPrev.Visible = dtSearchResult.Rows.Count > 0 ? true : false;
                btnNext.Visible = dtSearchResult.Rows.Count > 0 ? true : false;

                lblPageText.Visible = dtSearchResult.Rows.Count > 0 ? true : false;
                lnkSaveBookmarks.Visible = dtSearchResult.Rows.Count > 0 ? true : false;

                grdBingSearch.Visible = false;
                grdUKPMCSearch.Visible = true;
                lnkUKPMCSearch.Attributes.Add("style", "font-weight:bold;");
                lnkBingSearch.Attributes.Add("style", "font-weight:normal;");

                total = totalResults;
                ViewState["total"] = total;
                if (total > 0) // If the search results are greater than zero
                {
                    if ((offset + Convert.ToUInt32(ViewState["itemsperpage"])) < total)
                        lblPageText.Text = (offset + 1).ToString() + "-" + (offset + Convert.ToUInt32(ViewState["itemsperpage"])).ToString() + " of " + total.ToString();
                    else
                        lblPageText.Text = (offset + 1).ToString() + "-" + total.ToString() + " of " + total.ToString();

                    EnableDisableButtons(searchOffset, total);
                    btnSaveQuery.ImageUrl = "~/_layouts/SearchLiterature/Save-Query.png";
                    btnSaveQuery.Enabled = true;
                }
                else
                {
                    lblResults.Text = "We didn't find any results for " + txtSearch.Text;
                    lblPageText.Text = string.Empty;
                    btnNext.Enabled = false;
                    btnPrev.Enabled = false;
                    grdUKPMCSearch.DataSource = null;
                    grdUKPMCSearch.DataBind();
                }

            }
            catch
            {
                lblResults.Text = "We didn't find any results for " + txtSearch.Text;
                lblPageText.Text = string.Empty;
                btnNext.Enabled = false;
                btnPrev.Enabled = false;
                grdUKPMCSearch.DataSource = null;
                grdUKPMCSearch.DataBind();
            }
        }


        // Enable/Disable previous and next buttons according to the total results and current page
        private void EnableDisableButtons(uint searchOffset, uint total)
        {
            try
            {
                if (total >= 0 && total <= Convert.ToUInt32(ViewState["itemsperpage"])) // Both Prev and Next Disable
                {
                    btnNext.Enabled = false;
                    btnPrev.Enabled = false;
                    btnNext.ImageUrl = "~/_layouts/SearchLiterature/next-disable.png";
                    btnPrev.ImageUrl = "~/_layouts/SearchLiterature/prev-disable.png";
                }
                else
                {
                    if (offset + Convert.ToUInt32(ViewState["itemsperpage"]) >= total) // Prev Enable And Next Disable
                    {
                        btnNext.Enabled = false;
                        btnPrev.Enabled = true;
                        btnNext.ImageUrl = "~/_layouts/SearchLiterature/next-disable.png";
                        btnPrev.ImageUrl = "~/_layouts/SearchLiterature/prev.png";
                    }
                    else
                    {
                        if (offset + Convert.ToUInt32(ViewState["itemsperpage"]) < total && offset == 0) // Prev Disable And Next Enable
                        {
                            btnNext.Enabled = true;
                            btnPrev.Enabled = false;
                            btnNext.ImageUrl = "~/_layouts/SearchLiterature/next.png";
                            btnPrev.ImageUrl = "~/_layouts/SearchLiterature/prev-disable.png";
                        }
                        else
                        {
                            if (offset + Convert.ToUInt32(ViewState["itemsperpage"]) < total && offset > 0) // Both Enable
                            {
                                btnNext.Enabled = true;
                                btnPrev.Enabled = true;
                                btnNext.ImageUrl = "~/_layouts/SearchLiterature/next.png";
                                btnPrev.ImageUrl = "~/_layouts/SearchLiterature/prev.png";
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }

        // Show the previous ten results
        protected void btnPrev_Click(object sender, EventArgs e)
        {
            try
            {
                if (ViewState["offset"] == null)
                    offset = 0;
                else
                    offset = Convert.ToUInt32(ViewState["offset"].ToString());

                if (offset >= 0)
                {
                    offset -= Convert.ToUInt32(ViewState["itemsperpage"]);
                    ViewState["ukpmcpage"] = Convert.ToUInt32(ViewState["ukpmcpage"].ToString()) - 1;
                    SearchAndBindText(offset);
                }

                ViewState["offset"] = offset;
            }
            catch
            {

            }
        }

        // Show the next ten results
        protected void btnNext_Click(object sender, EventArgs e)
        {
            try
            {
                total = Convert.ToUInt32(ViewState["total"].ToString());
                if (ViewState["offset"] == null)
                    offset = 0;
                else
                    offset = Convert.ToUInt32(ViewState["offset"].ToString());

                if (offset <= total)
                {
                    offset += Convert.ToUInt32(ViewState["itemsperpage"]);
                    ViewState["ukpmcpage"] = Convert.ToUInt32(ViewState["ukpmcpage"].ToString()) + 1;
                    SearchAndBindText(offset);
                }
                ViewState["offset"] = offset;
            }
            catch
            {
            }
        }


        // Create Bookmarks list
        private void AddBookmarksList()
        {
            try
            {
                Boolean chkListExists;
                chkListExists = SharepointManager.ListExists(SPContext.Current.Web, "Bookmarks");

                if (!chkListExists)
                {
                    SharepointManager.CreateNewList("Bookmarks", "Bookmarks List", SPListTemplateType.GenericList);
                }


                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb webCurrent = site.OpenWeb())
                    {
                        webCurrent.AllowUnsafeUpdates = true;
                        SPList list = webCurrent.Lists["Bookmarks"];
                        list.OnQuickLaunch = true;

                        Boolean chkFieldExists = list.Fields.ContainsField("URL");

                        if (list != null && !chkFieldExists)
                        {
                            list.Fields.Add("URL", SPFieldType.Text, true);
                            list.Fields.Add("Description", SPFieldType.Note, true);
                            list.Fields.Add("Search Text", SPFieldType.Text, true);
                            list.Update();

                            SPView view = list.DefaultView;
                            view.ViewFields.Add("URL");
                            view.ViewFields.Add("Search Text");
                            view.ViewFields.Add("Created By");
                            //view.ViewFields.Add("Created");
                            // Added by Jyoti on 7 march 2011 to show the most recent record to be appear at top                            view.Query = "<OrderBy><FieldRef Name='Created' Ascending='FALSE' /></OrderBy>";
                            view.Query = "<OrderBy><FieldRef Name='Created' Ascending='FALSE' /></OrderBy>";
                            view.Update();
                        }
                    }
                }

            }
            catch
            {
                lblResults.Text = "You don't have sufficient priviledges to manage list";
            }
        }

        // Create Saved Query List
        private void AddSavedQueryList()
        {
            
            try
            {
                Boolean chkListExists;


                chkListExists = SharepointManager.ListExists(SPContext.Current.Web, "Saved Queries");

                if (!chkListExists)
                {
                     SharepointManager.CreateNewList("Saved Queries", "Saved List", SPListTemplateType.GenericList);
                }

                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb webCurrent = site.OpenWeb())
                    {
                        webCurrent.AllowUnsafeUpdates = true;
                        SPList list = webCurrent.Lists["Saved Queries"];
                        list.OnQuickLaunch = true;

                        Boolean chkFieldExists = list.Fields.ContainsField("URL");

                        if (list != null && !chkFieldExists)
                        {
                            list.Fields.Add("Query Description", SPFieldType.Text, true);
                            list.Fields.Add("URL", SPFieldType.URL, true);
                            list.Update();

                            SPView view = list.DefaultView;
                            view.ViewFields.Add("Query Description");
                            view.ViewFields.Add("URL");
                            view.ViewFields.Add("Created By");
                            //view.ViewFields.Add("Created");
                            // Added by Jyoti on 7 march 2011 to show the most recent record to be appear at top
                            view.Query = "<OrderBy><FieldRef Name='Created' Ascending='FALSE' /></OrderBy>";
                            view.Update();
                        }
                    }
                }

            }
            catch
            {
                lblResults.Text = "You don't have sufficient priviledges to manage list";
            }
           
        }

        // Open a different view to enter save query description
        protected void btnSaveQuery_Click(object sender, EventArgs e)
        {
            mvwStudyPlanning.ActiveViewIndex = 1;
            pnlQueryDesc.Visible = true;
            btnSaveQuery.ImageUrl = "~/_layouts/SearchLiterature/Save-Query-disable.png";
            btnSaveQuery.Enabled = false;
            txtQuery.Text = txtSearch.Text;
            txtQueryDesc.Text = String.Empty;
        }

        // Enter Save Query details in the list
        protected void btnSave_Click(object sender, EventArgs e)
        {
            string urlFile;
            string[] arryCurrentUrl;
            try
            {
                arryCurrentUrl = Request.Url.ToString().Split(new char[] { '?' });
                urlFile = arryCurrentUrl[0].ToString();
                if (urlFile == null)
                {
                    urlFile = Request.Url.ToString();
                }
            }
            catch (Exception ex)
            {
                urlFile = Request.Url.ToString();
            }

            string key3 = String.Empty;
            string key4 = String.Empty;
            string searchText;
            searchText = txtSearch.Text;
            searchText = searchText.Replace(" ", "%20");


            if (chkSearchSources.Items[0].Selected == true)
                key3 = "&key3=true";
            else
                key3 = "&key3=false";


            if (chkSearchSources.Items[1].Selected == true)
                key4 = "&key4=true";
            else
                key4 = "&key4=false";

            string urlFull = urlFile + "?key1=" + searchText + "&key2=" + ViewState["CurrentSearch"].ToString() + key3 + key4;

            SPSite site = SPContext.Current.Site;
            SPWeb web = site.OpenWeb();
            SPUser user = web.CurrentUser;
            web.AllowUnsafeUpdates = true;
            SPList list = web.Lists["Saved Queries"];

            SPListItem listItem = list.Items.Add();

            listItem["Title"] = txtSearch.Text;
            listItem["Query Description"] = txtQueryDesc.Text;
            listItem["URL"] = urlFull.ToString();
            listItem.Update();

            lblResults.Text = "Your query has been saved successfully.";
            MessageBox("Your query has been saved successfully.");

            pnlQueryDesc.Visible = false;
            btnSaveQuery.ImageUrl = "~/_layouts/SearchLiterature/Save-Query.png";
            btnSaveQuery.Enabled = true;
            mvwStudyPlanning.ActiveViewIndex = 0;
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            pnlQueryDesc.Visible = false;
            btnSaveQuery.ImageUrl = "~/_layouts/SearchLiterature/Save-Query.png";
            btnSaveQuery.Enabled = true;
            mvwStudyPlanning.ActiveViewIndex = 0;
        }

        // Save the selected search results in the Bookmarks list
        protected void lnkSaveBookmarks_Click(object sender, EventArgs e)
        {
            try
            {

                string Title, URL, Description;

                Boolean flag = false;
                int rowCount = 0;

               
              
                if (ViewState["CurrentSearch"].ToString() == "UKPMC")
                    rowCount = grdUKPMCSearch.Rows.Count;
                else
                    rowCount = grdBingSearch.Rows.Count;
                

                //Get the value of selected checkboxes from the GridView control
                for (int i = 0; i < rowCount; i++)
                {
                    GridViewRow row;

                    if (ViewState["CurrentSearch"].ToString() == "UKPMC")
                        row = grdUKPMCSearch.Rows[i];
                    else
                        row = grdBingSearch.Rows[i];


                    bool isChecked = ((CheckBox)row.FindControl("chkSearch")).Checked;

                    if (isChecked)
                    {
                        flag = true;
                        Title = ((Label)row.FindControl("lblTitle")).Text;
                        URL = ((Label)row.FindControl("lblURL")).Text;
                        Description = ((Label)row.FindControl("lblDescription")).Text;

                        SPSite site = SPContext.Current.Site;
                        SPWeb web = site.OpenWeb();
                        SPUser user = web.CurrentUser;
                        web.AllowUnsafeUpdates = true;
                        SPList list = web.Lists["Bookmarks"];

                        SPListItem listItem = list.Items.Add();

                        listItem["Title"] = Title;
                        listItem["URL"] = URL;
                        listItem["Description"] = Description;
                        listItem["Search Text"] = txtSearch.Text;
                        listItem.Update();
                    }
                }

                if (!flag)
                {
                    lblResults.Text = "Please select a record.";
                    MessageBox("Please select a record.");
                }
                else
                {
                    lblResults.Text = "Selected records have been bookmarked successfully. ";
                    MessageBox("Selected records have been bookmarked successfully. ");
                }
            }
            catch
            {
                lblResults.Text = "You don't have sufficient privileges to add to the Bookmarks List.";
                MessageBox("You don't have sufficient privileges to add to the Bookmarks List.");
            }

        }


        // Set the default values before starting the search
        protected void ResetValues()
        {
            lblResults.Text = String.Empty;
            lblPageText.Text = String.Empty;
            offset = 0;
            ViewState["offset"] = 0;
            ViewState["total"] = 0;
            ViewState["itemsperpage"] = 10;
            ViewState["ukpmcpage"] = 1;
        }
    }
}
